//
//  ZLAlert.swift
//  ZLAlert
//
//  Created by ZL on 2022/11/24.
//

import UIKit
import Lottie

public class ZLActivityIndicator: UIView {
    private lazy var animationBgView: UIView = {
        let view = UIView()
        view.backgroundColor = .white//UIColor(red: 0.91, green: 0.91, blue: 0.91, alpha: 1)
        view.layer.cornerRadius = 5
        view.layer.masksToBounds = true
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    private lazy var animationView: LottieAnimationView = {
        let animationView = LottieAnimationView(name: "loading_circle", bundle: self.currentBundle())
        animationView.frame = CGRect(x: -30, y: -30, width: 120, height: 120)
        animationView.loopMode = .loop
        animationView.contentMode = .scaleAspectFit
        animationView.animationSpeed = 1.0
        return animationView
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(animationBgView)
        animationBgView.addSubview(animationView)
        NSLayoutConstraint.activate([
            animationBgView.widthAnchor.constraint(equalToConstant: 60),
            animationBgView.heightAnchor.constraint(equalToConstant: 60),
            animationBgView.centerXAnchor.constraint(equalTo: centerXAnchor),
            animationBgView.centerYAnchor.constraint(equalTo: centerYAnchor),
        ])
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

public extension ZLActivityIndicator {
    func startAnimating() {
        self.superview?.bringSubviewToFront(self)
        self.isHidden = false
        self.animationView.play()
    }
    func stopAnimating() {
        self.isHidden = true
        self.animationView.stop()
    }
}

extension ZLActivityIndicator {
    func currentBundle() -> Bundle {
        let bundle = Bundle(for: ZLActivityIndicator.self)
        guard let bundlePath = bundle.path(forResource: "ZLActivityIndicatorBundle", ofType: "bundle") else {
            return Bundle.main
        }
        return Bundle(path: bundlePath) ?? Bundle.main
    }
}
